<template>
  <div>
    <div v-if="mode === 'DESIGN'">
      <div class="design">
        <el-icon><Plus /></el-icon>
      </div>
      <p style="margin-top:12px;">{{ placeholder }} {{ sizeTip }}</p>
    </div>
    <div v-else-if="mode === 'PC' && !readonly">
      <el-upload :file-list="fileList" :action="uploadUrl" :limit="maxNumber" with-credentials :multiple="maxNumber > 1"
        :headers="headers" :on-success="uploadSuccess" :on-preview="handlePictureCardPreview" :on-remove="handleRemove"
        :on-exceed="overLimit" :on-error="uploadFail" list-type="picture-card" auto-upload :before-upload="beforeUpload">
        <template #default>
            <el-icon><Plus /></el-icon>
        </template>
        <template #tip>
          <div class="el-upload__tip">{{ placeholder }} {{ sizeTip }}</div>
        </template>
      </el-upload>
    </div>
    <div v-else-if="mode === 'MOBILE' && !readonly">
      <uploader v-model="fileList" :multiple="maxNumber > 1" :max-count="maxNumber > 0 ? maxNumber : 99"
        deletable :before-delete="handleRemove" :before-read="beforeUpload" upload-text="选择图片" :after-read="afterRead"
        :max-size="maxSize * 1024 * 1024" @oversize="onOversize"/>
      <div style="color: #9b9595">{{ placeholder }} {{ sizeTip }}</div>
    </div>
    <div v-else class="img-preview">
      <div class="img-preview-pc">
        <el-image :alt="img.name" :src="$getRes(img.url)" v-for="img in _value" :key="img.id" :preview-src-list="pcImgList"></el-image>
      </div>
    </div>
  </div>
</template>

<script>
import { Uploader, showSuccessToast, showFailToast } from 'vant'
import componentMinxins from '/@/views/setting/workflow/components/ComponentMinxins'
import { Plus } from '@element-plus/icons-vue'
import { computed, reactive, toRefs } from 'vue'
import { Session } from '/@/utils/storage'
import { getRes } from '/@/utils/utils'
import { ElMessage } from 'element-plus'
import request from '/@/utils/request'

export default {
    name: 'ImageUpload',
    mixins: [componentMinxins],
    components: { Uploader, Plus },
    props: {
        modelValue: {
            type: Array,
            default: () => {
                return []
            },
        },
        placeholder: {
            type: String,
            default: '请选择图片',
        },
        maxSize: {
            type: Number,
            default: 5,
        },
        maxNumber: {
            type: Number,
            default: 10,
        },
        enableZip: {
            type: Boolean,
            default: true,
        },
    },
    emits: ['update:modelValue'],
    setup(props, context) {
        const { maxSize, mode, maxNumber, modelValue } = toRefs(props)
        const state = reactive({
            loading: false,
            disabled: false,
            uploadUrl: `/api/file/filaAttach/upload`,
            headers: { 
              '17work': Session.get('token')
            },
            catchList: [],
            alows: ['image/jpeg', 'image/png', 'image/gif', 'image/jpg'],
        })
        const _value = computed({
            get: () => {
                return modelValue.value
            },
            set: val => {
                context.emit('update:modelValue', val)
            }
        })
        const sizeTip = computed(() => {
            return maxSize.value > 0 ? `| 每张图不超过${maxSize.value}MB` : ''
        })
        const pcImgList = computed(() => {
          return _value.value.map((v) => v.url)
        })
        const fileList = computed({
          get: () => {
            return _value.value.map((f) => {
              return {
                name: f.name,
                url: f.src,
                status: 'success',
              }
            })
          },
          set: val => {}
        })
        const beforeUpload = (file) => {
          state.catchList.length = 0
          if (Array.isArray(file)) {
            for (let i = 0; i < file.length; i++) {
              if (!validImage(file[i])) {
                return false
              }
            }
            return true
          } else {
            return validImage(file)
          }
        }
        const validImage = img => {
          if (state.alows.indexOf(img.type) === -1) {
            ElMessage.warning('存在不支持的图片格式')
          } else if (maxSize.value > 0 && img.size / 1024 / 1024 > maxSize.value) {
            ElMessage.warning(`单张图片最大不超过 ${maxSize.value}MB`)
          } else {
            state.loading = true
            return true
          }
          return false
        }
        const removeFile = (fileId) => {
          // TO DO 这里调接口
          return
          ElMessage.success('移除文件成功')
        }
        const uploadSuccess = (response, file, fileList) => {
          state.loading = false
          state.catchList.push(response.data)
          let ft = fileList.filter((f) => f.size !== undefined)
          if (state.catchList.length === ft.length) {
            _value.value.push(...state.catchList)
            context.emit('update:modelValue', _value.value)
          }
          ElMessage.success(response.data.name + '上传成功')
        }
        const uploadFail = (err) => {
          state.loading = false
          ElMessage.error('图片上传失败 ' + err)
        }
        const afterRead = (file) => {
          if (Array.isArray(file)) {
            file.forEach((fl) => {
              uploadFile(fl)
            })
          } else {
            uploadFile(file)
          }
        }
        const uploadFile = (file) => {
          //上传文件
          const formData = new FormData()
          formData.append('file', file.file)
          formData.append('isImg', true)
          request({
            url: state.uploadUrl,
            method: 'post',
            data: formData,
            headers: {
              'Content-type': 'multipart/form-data',
              '17work': Session.get('token')
            }
          }).then(
            (res) => {
              if (res.code === 0) {
                _value.value.push(res.data)
                context.emit('update:modelValue', _value.value)
                showSuccessToast('上传成功')
              }
            },
            (err) => {
              showFailToast('上传失败')
              console.log(err)
            }
          )
        }
        const overLimit = () => {
          if (mode.value === 'PC') {
            ElMessage.warning('最多只能上传' + maxNumber.value + '张图片')
          } else {
            showFailToast('数量超出限制')
          }
        }
        const onOversize = (file) => {
          showFailToast('图片过大')
        }
        const handleRemove = (file, fileList) => {
          let i = _value.value.findIndex((v) => v.name === file.name)
          if (i > -1) {
            //removeFile(_value.value[i].id)
            _value.value.splice(i, 1)
            context.emit('update:modelValue', _value.value)
          }
          console.log('删除文件', file)
        }
        const handlePictureCardPreview = (file) => {
          console.log(file)
        }
        const handleDownload = (file) => {
          console.log(file)
        }
        return {
            ...toRefs(state),
            sizeTip,
            pcImgList,
            fileList,
            beforeUpload,
            validImage,
            removeFile,
            uploadSuccess,
            uploadFail,
            afterRead,
            overLimit,
            onOversize,
            handleRemove,
            handlePictureCardPreview,
            handleDownload,
            _value
        }
    }
}
</script>

<style lang="scss" scoped>
.design {
  :deep(.el-icon) {
    padding: 10px;
    font-size: 52px;
    background: white;
    border: 1px dashed #8c8c8c;
  }
}
:deep(.el-upload--picture-card) {
  width: 80px;
  height: 80px;
  line-height: 87px;
}
:deep(.el-upload-list__item) {
  width: 80px;
  height: 80px;
  transition: none;
  .el-upload-list__item-actions {
    & > span + span {
      margin: 1px;
    }
  }
}
:deep(.el-upload-list__item-preview) {
  display: none !important;
}
.img-preview {
  :deep(.img-preview-pc) {
    .el-image {
      width: 80px;
      height: 80px;
      margin: 5px;
    }
  }
}
</style>